package com.yileiqian.alg;

import java.util.Random;

public class RandomGenerate {

	private static Random random;

	static {
		random = new Random();
	}

	public static boolean happens() {
		return random.nextBoolean();
	}

	public static boolean happens(double probability) {
		if (probability <= 0) {
			return false;
		}
		if (probability >= 1) {
			return true;
		}

		double range = 1.0;
		double begin = 0.0;
		boolean bool = true;

		while (true) {
			range /= 2;
			bool = random.nextBoolean();

			if (probability == begin + range) {
				return bool;
			} else if (probability > begin + range) {
				if (bool) {
					return true;
				}
				begin = begin + range;
			} else {
				if (!bool) {
					return false;
				}
			}
		}
	}

	public static void main(String args[]) {
		int n = 1000000000;
		int count = 0;
		for (int i = 0; i < n; i++) {
			if (happens(.5150)) {
				count++;
			}
		}

		System.out.println((double) count / n);
	}
}
